<template>
  <el-form-item label="图片" required>
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :on-change="handleImageChange"
      :before-upload="beforeUpload"
      accept="image/*"
    >
    <img 
      v-if="imageUrl" 
      :src="imageUrl" 
      alt="菜品图片" 
      class="avatar"
      :style="{ width: defaultSize + 'px', height: defaultSize + 'px' }" 
    />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    
  </el-form-item>
</template>

<script>
export default {
  props: {
    value: String,
    defaultSize: {
      type: Number,
      default: 200 // 默认大小为200px
    }
  },
  data() {
    return {
      imageUrl: this.value
    };
  },
  methods: {
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB');
      }

      return isImage && isLt2M;
    },
    async handleImageChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.imageUrl = e.target.result; // 将图片URL设置为base64格式
        this.$emit('input', this.imageUrl); // 触发 input 事件，传递图片 URL
      };
      reader.readAsDataURL(file.raw); // 读取文件
    }
  },
  watch: {
    value(newVal) {
      this.imageUrl = newVal;
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
